{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from utils import tokenize, load_curpus\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "#### 加载数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Building prefix dict from the default dictionary ...\n",
      "Loading model from cache /var/folders/dy/xjy0y7v97js5x1bghby2fnkm0000gn/T/jieba.cache\n",
      "Loading model cost 0.702 seconds.\n",
      "Prefix dict has been built succesfully.\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "train_data = load_curpus(\"weibo2018/train.txt\")\n",
    "test_data = load_curpus(\"weibo2018/test.txt\")\n",
    "train_df = pd.DataFrame(train_data, columns=[\"content\", \"sentiment\"])\n",
    "test_df = pd.DataFrame(test_data, columns=[\"content\", \"sentiment\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "stopwords = []\n",
    "with open(\"stopwords.txt\", \"r\", encoding=\"utf8\") as f:\n",
    "    for w in f:\n",
    "        stopwords.append(w.strip())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Ont-hot\n",
    "ps: 与其他方法相比，朴素贝叶斯并没有对高质量词向量的需求，因此不再加载Fasttext词向量，而是直接用one-hot形式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<10500x38718 sparse matrix of type '<class 'numpy.int64'>'\n",
       "\twith 172234 stored elements in Compressed Sparse Row format>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.feature_extraction.text import CountVectorizer\n",
    "data_str = [\" \".join(content) for content, sentiment in train_data] + \\\n",
    "            [\" \".join(content) for content, sentiment in test_data]\n",
    "vectorizer = CountVectorizer(token_pattern='\\[?\\w+\\]?', stop_words=stopwords)\n",
    "vectorizer.fit_transform(data_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "X_data, y_data = [], []\n",
    "for content, sentiment in train_data:\n",
    "    X, y = [], sentiment\n",
    "    X_data.append(\" \".join(content))\n",
    "    y_data.append(sentiment)\n",
    "X_train = vectorizer.transform(X_data)\n",
    "y_train = y_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "X_data, y_data = [], []\n",
    "for content, sentiment in test_data:\n",
    "    X, y = [], sentiment\n",
    "    X_data.append(\" \".join(content))\n",
    "    y_data.append(sentiment)\n",
    "X_test = vectorizer.transform(X_data)\n",
    "y_test = y_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Bayes\n",
    "全部用默认参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.naive_bayes import MultinomialNB\n",
    "clf = MultinomialNB()\n",
    "clf.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "result = clf.predict(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 模型评估\n",
    "速度快，效果还很好，可能是因为该任务语料规模较小，在大规模语料任务上性能会下降"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "             precision    recall  f1-score   support\n",
      "\n",
      "          0       0.73      0.86      0.79       155\n",
      "          1       0.93      0.86      0.89       345\n",
      "\n",
      "avg / total       0.87      0.86      0.86       500\n",
      "\n",
      "准确率: 0.858\n"
     ]
    }
   ],
   "source": [
    "from sklearn import metrics\n",
    "print(metrics.classification_report(y_test, result))\n",
    "print(\"准确率:\", metrics.accuracy_score(y_test, result))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "metadata": {
     "collapsed": false
    },
    "source": []
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
